#pragma once
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <cstring>
#include <string>
#include <strings.h>
#include <functional>
#include "log.hpp"

using func_t = std::function<std::string(const std::string&)>;
Log lg;
const std::string defaultip = "0.0.0.0";
const uint16_t defaultport = 8080;
const int size = 1024;

enum{
    CREAT_ERR = 1,
    BIND_ERR = 2
};

class UpdServer{
public:
    UpdServer(const uint16_t& port = defaultport, const std::string& ip = defaultip)
    :_sockfd(0),
    _port(port),
    _ip(ip),
    _isrunning(false)
    {}
    ~UpdServer()
    {
        if(_sockfd > 0) close(_sockfd);
    }
    void Init()
    {
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if(_sockfd < 0)
        {
            lg(Fatal, "socket create error, sockfd: %d\n", _sockfd);
            exit(CREAT_ERR);
        }
        lg(Info, "socket create success, sockfd: %d\n", _sockfd);
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = inet_addr(_ip.c_str());
        // local.sin_addr.s_addr = htonl(INADDR_ANY);

        if(bind(_sockfd, (const struct sockaddr*)&local, sizeof(local)) < 0)
        {
            lg(Fatal, "sock bind error, errno: %d, err string: %s\n", errno, strerror(errno));
            exit(BIND_ERR);
        }
        lg(Info, "bind success, errno: %d, err string: %s", errno, strerror(errno));

    }
    void Run(func_t func)
    {
        _isrunning = true;
        char inbuffer[size];
        while(_isrunning)
        {
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            ssize_t n = recvfrom(_sockfd, inbuffer, sizeof(inbuffer) - 1, 0, (struct sockaddr*)&client, &len);
            if(n < 0)
            {
                lg(Warning, "recvfrom error, errno: %d, err string: %s\n", errno, strerror(errno));
                continue;
            }
            inbuffer[n] = 0;
            // 数据处理
            std::string info = inbuffer;
            // std::string echo_info = "server echo# " + info;
            std::string echo_info = func(info);
            sendto(_sockfd, echo_info.c_str(), echo_info.size(), 0, (const struct sockaddr*)&client, len);
        }
    }

private:
    int _sockfd;
    std::string _ip;
    uint16_t _port;
    bool _isrunning;
};